package com.bigfish.gbs.controller;

import com.bigfish.gbs.dto.Result;
import com.bigfish.gbs.entity.User;
import com.bigfish.gbs.service.AccountService;
import com.bigfish.gbs.service.UserService;
import com.bigfish.gbs.util.*;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 账户登陆注册
 * @author Joycessh
 * @date 12/3/18 10:15 AM
 */
@RestController
@RequestMapping("/account")
@Api(value = "账户相关", description = "账户登录注册接口")
public class AccountController extends BasicAction {

    private static final Logger LOGGER = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AccountService accountService;

    @Autowired
    private UserService userService;


    /**
     * 用户登录,签发jwt
     * @author Joycessh
     * @param request
	 * @param response
     * @return com.bigfish.gbs.dto.Result
     * @date 12/3/18 10:16 AM
     */
    @ApiOperation(value = "用户登录", notes = "POST用户登录签发JWT")
    @PostMapping("/login")
    public Result accountLogin(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> params = RequestResponseUtil.getRequestBodyMap(request);
        String appId = params.get("appId");
        // 根据appId获取其对应所拥有的角色(这里设计为角色对应资源，没有权限对应资源)
        String roles = accountService.loadAccountRole(appId);
        // 时间以秒计算,token有效刷新时间是token有效过期时间的2倍
        long refreshPeriodTime = 36000L;
        String jwt = JsonWebTokenUtil.issueJWT(UUID.randomUUID().toString(), appId,
                "token-server", refreshPeriodTime >> 1, roles, null, SignatureAlgorithm.HS512);
        // 将签发的JWT存储到Redis： {JWT-SESSION-{appID} , jwt}
        redisTemplate.opsForValue().set("JWT-SESSION-" + appId, jwt, refreshPeriodTime, TimeUnit.SECONDS);
        User user = userService.getUserByAppId(appId);
        user.setPassword(null);
        user.setSalt(null);
        return ResultUtil.retParams(1003, "issue jwt success").addData("token", jwt).addData("user", user);
    }

    /**
     * 用户注册
     * @author Joycessh
     * @param
     * @return Message
     * @date 12/3/18 10:16 AM
     */
    @ApiOperation(value = "用户注册", notes = "POST用户注册")
    @PostMapping("/register")
    public Result accountRegister(HttpServletRequest request, HttpServletResponse response) {

        Map<String, String> params = RequestResponseUtil.getRequestBodyMap(request);
        User user = new User();
        String userId = params.get("appId");
        String password = params.get("password");
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(password)) {
            // 必须信息缺一不可,返回注册账号信息缺失
            return ResultUtil.retParams(1111, "账户信息缺失");
        }
        if (accountService.isAccountExistByUid(userId)) {
            // 账户已存在
            return ResultUtil.retParams(1111, "账户已存在");
        }

        user.setUserId(userId);

        // 从Redis取出密码传输加密解密秘钥
        //String tokenKey = redisTemplate.opsForValue().get("TOKEN_KEY_" + IpUtil.getIpFromRequest(WebUtils.toHttp(request)).toUpperCase()+userKey);
        //String realPassword = AESUtil.aesDecode(password, tokenKey);
        String salt = CommonUtil.getRandomString(6);
        // 存储到数据库的密码为 MD5(原密码+盐值)
        user.setPassword(MD5Util.md5(password + salt));
        user.setSalt(salt);
        user.setCreateTime(new Date());
        if (!StringUtils.isEmpty(params.get("username"))) {
            user.setUsername(params.get("username"));
        }
        if (!StringUtils.isEmpty(params.get("realName"))) {
            user.setRealName(params.get("realName"));
        }
        if (!StringUtils.isEmpty(params.get("avatar"))) {
            user.setAvator(params.get("avatar"));
        }
        if (!StringUtils.isEmpty(params.get("phone"))) {
            user.setPhone(params.get("phone"));
        }
        if (!StringUtils.isEmpty(params.get("email"))) {
            user.setMail(params.get("email"));
        }
        if (!StringUtils.isEmpty(params.get("sex"))) {
            user.setSex(Byte.valueOf(params.get("sex")));
        }
        user.setStatus((byte) 1);
        System.out.println("注册start....");
        if (accountService.registerAccount(user)) {
            //LogExeManager.getInstance().executeLogTask(LogTaskFactory.registerLog(uid, IpUtil.getIpFromRequest(WebUtils.toHttp(request)), (short) 1, "注册成功"));
            return ResultUtil.retParams(2002, "注册成功");

        } else {
            //LogExeManager.getInstance().executeLogTask(LogTaskFactory.registerLog(uid, IpUtil.getIpFromRequest(WebUtils.toHttp(request)), (short) 0, "注册失败"));
            return ResultUtil.retParams(1111, "注册失败");
        }


}}
